# -*- coding: utf-8 -*-

# Copyright (c) 2011, Sergey Karakovskiy, Nikolay Sohryakov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Yasker nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import logging
from google.appengine.api import users, xmpp, memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from app import yasker_protocol
from app.anyjson import simplejson
from app.datastore import events
from app.datastore import ds_adaptor

from app.datastore.Keys import *

__author__ = 'Nikolay Sohryakov, Sergey Karakovskiy'
__copyright__ = 'Copyright 2011, Yasker'
__license__ = 'New BSD'
__email__ = 'Nikolay.Sohryakov+yasker@gmail.com, Sergey.Karakovskiy+yasker@gmail.com'

#TODO:*:!H!:move class to separate file
class XMPPRequestsHandler(webapp.RequestHandler):
	def post(self):
		message = xmpp.Message(self.request.POST)
		sender = message.sender.split('/')[0].lower()
		resource = message.sender.split('/')[1].lower()
		#TODO: resource is something like yaskerFC4D1856. fix it.
#		logging.debug(''.join(('xmpp resource: ', resource)))
#		logging.debug(''.join(('xmpp sender: ', sender)))
#		if not yasker_protocol.is_authorized(sender) or resource != 'yasker':
#			# ignore this user
#			return
		memcache.add('sender', sender)
#		logging.debug(message.body)
		yasker_request = simplejson.loads(message.body)
#		logging.debug(yasker_request)
#		logging.debug(type(yasker_request))
		request_type = yasker_request['type']
#		logging.debug(''.join(('request type: ', request_type)))
		if request_type == TYPE_GET:
			result = yasker_protocol.get(yasker_request)
		elif request_type == TYPE_ADD:
			result = yasker_protocol.add(yasker_request)
		elif request_type == TYPE_UPDATE:
			result = yasker_protocol.update(yasker_request)
		elif request_type == TYPE_DELETE:
			result = yasker_protocol.delete(yasker_request)
		else:
			result = 106, 'Unknown request type'
		if result[0] in (204, 205, 206):
			users = ds_adaptor.get_authorized_users_list()
			# send an update for each user who is online or put an update
			# in to the updates storage.
			for user in users:
#				if xmpp.get_presence('/'.join((user, 'yasker'))):
				if xmpp.get_presence(user):
					if user != sender:
						xmpp.send_message(user, simplejson.dumps(result))
#						xmpp.send_message(''.join((user, '/yasker')),
#						                  simplejson.dumps(result))
				else:
					events.add_event(user, simplejson.dumps(result))

		message.reply(simplejson.dumps(result))


class MainHandler(webapp.RequestHandler):
	"""
	Handles everything except XMPP messages.
	"""

	def get(self):
		args = {
			'logout_url': users.create_logout_url('/')
		}
		self.response.out.write(template.render('templates/index.html', args))


def main():
	logging.getLogger().setLevel(logging.DEBUG)
	application = webapp.WSGIApplication(
		[
				('/', MainHandler),
				('/_ah/xmpp/message/chat/', XMPPRequestsHandler),
		                          ], debug=True)

	run_wsgi_app(application)


if __name__ == '__main__':
	main()
